import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfoAPI } from '@/api/userAPI'

Vue.use(Vuex)

// 默认数据
let initState = {
  tokenInfo: {}, // 放token retoken
  userInfo: {} // 用户的基本信息
}
const allStateObj = JSON.parse(localStorage.getItem('newsState'))
if (allStateObj) {
  initState = allStateObj
}
export default new Vuex.Store({
  state: initState,
  getters: {
    userInfo1: (state) => {
      return state.userInfo
    }
  },
  mutations: {
    saveTokenInfo(state, token) {
      state.tokenInfo = token
      this.commit('saveStatetoStorage')
    },
    saveStatetoStorage(state) {
      localStorage.setItem('newsState', JSON.stringify(state))
    },
    updateUserInfo(state, info) {
      state.userInfo = info
      localStorage.setItem('newsState', JSON.stringify(state))
    },
    cleanLocalData(state) {
      state.userInfo = {}
      state.tokenInfo = {}
      localStorage.setItem('newsState', JSON.stringify(state))
    }
  },
  actions: {
    async initUserInfo(context) {
      const { data: res } = await getUserInfoAPI()
      if (res.message === 'OK') {
        // 在action里触发mutation的方法updateUserInfo
        context.commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {}
})
